'use strict'

const semver = require('semver')
const colors = require('colors/safe')
const log = require('@lenovo-cli/log')

const LOWEST_NODE_VERSION = '12.0.0'

class Command {
  constructor(argv) {
    this.validate(argv)
    this._argv = argv
    new Promise((resolve, reject) => {
      let chain = Promise.resolve()
      chain = chain.then(() => {
        this.checkNodeVersion()
      })
      chain = chain.then(() => {
        this.initArgs()
      })
      chain = chain.then(() => {
        this.init()
      })
      chain = chain.then(() => {
        this.exec()
      })

      // 新建一个Promise，需要catch处理
      chain.catch(err => {
        log.error(err.message)
      })
    })
  }
  validate(argv) {
    if (!argv) {
      throw new Error('Class Command参数不能为空！')
    }
    if (!Array.isArray(argv)) {
      throw new Error('Class Command参数必须为数组！')
    }
    if (argv.length < 1) {
      throw new Error('Class Command参数列表不能为空！')
    }
  }

  // 检查node版本号
  checkNodeVersion() {
    // 当前版本号与最低版本号比对
    const lowestVersion = LOWEST_NODE_VERSION
    if (!semver.gte(process.version, lowestVersion)) {
      // 当前版本号没有大于最低版本号
      throw new Error(
        colors.red(`lenovo-cli 需要安装 v${lowestVersion} 以上版本的 node.js`)
      )
    }
  }

  initArgs() {
    this._cmd = this._argv[this._argv.length - 1]
    this._argv = this._argv.slice(0, this._argv.length - 1)
  }

  init() {
    throw new Error('init必须实现')
  }
  exec() {
    throw new Error('exec必须实现')
  }
}

module.exports = Command
